"""
白名单数据模型
"""
from typing import Optional, List, Dict, Any
from datetime import datetime
from enum import Enum
from pydantic import BaseModel, Field, field_validator


class WhitelistType(str, Enum):
    """白名单类型"""
    DOMAIN = "domain"  # 域名级别
    URL = "url"  # URL级别
    PATTERN = "pattern"  # 正则模式
    SOURCE = "source"  # 来源标识


class WhitelistStatus(str, Enum):
    """白名单状态"""
    ACTIVE = "active"
    INACTIVE = "inactive"
    PENDING = "pending"


class WhitelistEntry(BaseModel):
    """白名单条目模型"""
    id: Optional[str] = Field(None, description="白名单ID")
    type: WhitelistType = Field(..., description="白名单类型")
    value: str = Field(..., description="白名单值")
    name: str = Field(..., description="名称")
    description: Optional[str] = Field(None, description="描述")
    status: WhitelistStatus = Field(default=WhitelistStatus.ACTIVE, description="状态")
    created_by: str = Field(..., description="创建者")
    created_at: datetime = Field(default_factory=datetime.now, description="创建时间")
    updated_at: datetime = Field(default_factory=datetime.now, description="更新时间")
    tags: List[str] = Field(default_factory=list, description="标签")
    metadata: Dict[str, Any] = Field(default_factory=dict, description="元数据")
    
    @field_validator('value')
    @classmethod
    def validate_value(cls, v: str, info) -> str:
        """验证白名单值"""
        if not v or not v.strip():
            raise ValueError("白名单值不能为空")
        return v.strip()
    
    @field_validator('type')
    @classmethod
    def validate_type_value_match(cls, v: WhitelistType, info) -> WhitelistType:
        """验证类型和值的匹配性"""
        # 这里可以添加更多的验证逻辑
        return v
    
    class Config:
        json_schema_extra = {
            "example": {
                "type": "domain",
                "value": "example.com",
                "name": "Example Domain",
                "description": "官方示例域名",
                "status": "active",
                "created_by": "admin",
                "tags": ["official", "trusted"]
            }
        }


class WhitelistMatchResult(BaseModel):
    """白名单匹配结果"""
    matched: bool = Field(..., description="是否匹配")
    entry: Optional[WhitelistEntry] = Field(None, description="匹配的条目")
    match_type: Optional[str] = Field(None, description="匹配类型")
    confidence: float = Field(1.0, description="匹配置信度")
    details: Dict[str, Any] = Field(default_factory=dict, description="匹配详情")


class WhitelistBatch(BaseModel):
    """批量操作模型"""
    entries: List[WhitelistEntry] = Field(..., description="条目列表")
    operation: str = Field(..., description="操作类型")
    
    @field_validator('entries')
    @classmethod
    def validate_batch_size(cls, v: List[WhitelistEntry]) -> List[WhitelistEntry]:
        """验证批量大小"""
        if len(v) > 1000:
            raise ValueError("批量操作最多支持1000条记录")
        return v


class WhitelistFilter(BaseModel):
    """白名单过滤器"""
    type: Optional[WhitelistType] = None
    status: Optional[WhitelistStatus] = None
    tags: Optional[List[str]] = None
    created_by: Optional[str] = None
    created_after: Optional[datetime] = None
    created_before: Optional[datetime] = None
    search_text: Optional[str] = None
    page: int = Field(default=1, ge=1)
    page_size: int = Field(default=20, ge=1, le=100)


class WhitelistStatistics(BaseModel):
    """白名单统计信息"""
    total_entries: int = Field(..., description="总条目数")
    active_entries: int = Field(..., description="活跃条目数")
    inactive_entries: int = Field(..., description="非活跃条目数")
    by_type: Dict[str, int] = Field(default_factory=dict, description="按类型统计")
    by_creator: Dict[str, int] = Field(default_factory=dict, description="按创建者统计")
    last_updated: datetime = Field(default_factory=datetime.now, description="最后更新时间")